'use strict';
var dayjs = require('dayjs')
var duration = require('dayjs/plugin/duration')
dayjs.extend(duration)
module.exports = {
    /**
     * XXXnameXXX
     * @url client/booths/kh/getBoothsInfo 前端调用的url参数地址
     * data 请求参数
     * @param {String} params1  参数1
     */
    main: async (event) => {
        let {
            data = {}, userInfo, util, filterResponse, originalParam
        } = event;
        let {
            customUtil,
            uniID,
            config,
            pubFun,
            vk,
            db,
            _
        } = util;
        let {
            uid
        } = data;
        let res = {
            code: 0,
            msg: ""
        };
        let row = '';

        let booths = await vk.baseDao.selects({
            dbName: "bidding-booths", // 主表名
            getMain: true,
            whereJson: {
                status: 1,
                endtime: _.nin(["", null])
            },
            // 副表列表
            foreignDB: [
                {
                    dbName: "bidding-biddingprices",
                    localKey: "_id",
                    foreignKey: "booth_id",
                    as: "biddingList",
                    limit: 500,
                    // 副表where条件
                    whereJson: {
                        status: _.neq(-1),
                    },
                    // 副表排序规则
                    sortArr: [{
                        "name": "_add_time",
                        "type": "desc"
                    }],

                },
                {
                    dbName: "bidding-session", // 副表名
                    localKey: "location", // 主表外键字段名
                    foreignKey: "place_id", // 副表外键字段名
                    as: "sessions",
                    whereJson: {
                        status: 3//已经结束
                    },
                    sortArr: [{
                        "name": "end",
                        "type": "desc"
                    }],
                    limit: 1000, // 当limit = 1时，以对象形式返回，否则以数组形式返回
                }
            ]
        });

        let biddingBoothSuccess = [];
        let notes_user = [];

        for (let index = 0; index < booths.length; index++) {
            const _booth = booths[index];
            let addBooth = {
                userid: '',
                booth_name: '',
                booth_id: '',
                price: 0,
            }

            //已经结束最后一场
            let session = _booth.sessions[0];

            if (vk.pubfn.isNotNull(_booth.endtime)) {

                if (vk.pubfn.isNotNull(_booth.inLast) && _booth.inLast && _booth.endtime > session.end) {

                    //处于最后竞价阶段
                    const date1 = dayjs(_booth.endtime)
                    const date2 = dayjs(new Date())
                    let biddinguser = _booth.biddingList[0];

                    let diffminutes = dayjs.duration(date2.diff(date1)).as('minutes');
                    console.log('离现在多少分钟')
                    console.log(diffminutes)
                    console.log('离现在多少分钟')
                    if (diffminutes > 0) {

                        //5分钟内没人竞标
                        addBooth.userid = biddinguser.userid;
                        addBooth.booth_name = _booth.name;
                        addBooth.booth_id = _booth._id;
                        addBooth.price = _booth.nowPrice;
                        biddingBoothSuccess.push(addBooth);
                    } else {
                        console.log("-----------inLastendtime");
                        console.log("-----------分钟");
                        console.log(date1.format('YYYY/MM/DD HH:mm:ss'));
                        console.log(dayjs.duration(date2.diff(date1)).as('minutes'))
                        console.log("-----------inLastendtime");
                    }
                } else {

                    const date1 = dayjs(_booth.endtime)
                    const date2 = dayjs(new Date())
                    let diffminutes = dayjs.duration(date2.diff(date1)).as('minutes');
                    console.log('离现在多少分钟')
                    console.log(diffminutes)
                    console.log('离现在多少分钟')
                    if (diffminutes > 0) {
                        //规定时间内结束
                        let biddinguser = _booth.biddingList[0];
                        addBooth.userid = biddinguser.userid;
                        addBooth.booth_name = _booth.name;
                        addBooth.booth_id = _booth._id;
                        addBooth.price = _booth.nowPrice;
                        biddingBoothSuccess.push(addBooth);
                    } else {

                    }

                }

            } else {
                //     //无人竞拍
            }
        }
        console.log('投标成功')
        console.log(biddingBoothSuccess)
        console.log('投标成功')


        for (let index = 0; index < biddingBoothSuccess.length; index++) {
            const transaction = await vk.baseDao.startTransaction();
            try {
                const success_booth = biddingBoothSuccess[index];

                let order_id = await vk.baseDao.add({
                    db: transaction,
                    dbName: "bidding-order",
                    dataJson: {
                        ...success_booth,
                        order_no: vk.pubfn.createOrderNo("NO_"),
                        status: 0,
                        mark: '竞拍成功待签合同'
                    }
                });
                if (vk.pubfn.isNotNull(order_id) && vk.pubfn.isNotNull(success_booth.booth_id)) {
                    let num = await vk.baseDao.updateById({
                        db: transaction,
                        dbName: "bidding-booths", // 表名
                        id: success_booth.booth_id,
                        dataJson: { // 需要修改的数据
                            status: 2,
                            endtime: '',
                            inLast: '',
                            order_id: order_id,
                            success_bidding_userid: success_booth.userid
                        }
                    });
                }
                let userinfo = await vk.baseDao.findById({
                    dbName: "uni-id-users",
                    id: success_booth.userid
                });
                await transaction.commit();
                notes_user.push(userinfo.mobile)
            } catch (err) {
                // 事务回滚
                await transaction.rollback();
                console.error(`transaction error`, err)
            }


        }

        if (notes_user.length > 0) {
            try {
                const sms_res = await uniCloud.sendSms({
                    appid: '__UNI__169CF09',
                    phoneList: notes_user,
                    templateId: '31471', // 请替换为自己申请的模板id
                    data: {
                        expMinute: '60',//失效时间
                    }
                })
            } catch (err) {
                // 调用失败
                console.log('短信发送失败')
                console.log(err.errCode)
                console.log(err.errMsg)
                return {
                    code: err.errCode,
                    msg: err.errMsg
                }
            }
        }




        // 业务逻辑结束-----------------------------------------------------------
        return biddingBoothSuccess;
    }
}